const express = require('express')
const cors = require('cors')
const mysql = require('mysql2/promise')

const app = express()
const port = process.env.PORT || 3001

// 数据库配置
const dbConfig = {
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '123456',
  database: 'movie_recommendation',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
}

// 创建数据库连接池
let pool
try {
  pool = mysql.createPool(dbConfig)
  console.log('数据库连接池创建成功')
} catch (error) {
  console.error('创建数据库连接池失败:', error)
  process.exit(1)
}

// 测试数据库连接
async function testDatabaseConnection() {
  try {
    const connection = await pool.getConnection()
    console.log('数据库连接测试成功')
    connection.release()
  } catch (error) {
    console.error('数据库连接测试失败:', error)
    console.error('请确保：')
    console.error('1. MySQL 服务已启动')
    console.error('2. 数据库配置正确：', dbConfig)
    console.error('3. 数据库和表已创建（运行 init.sql）')
    process.exit(1)
  }
}

// 中间件
app.use(cors())
app.use(express.json())

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

// 添加或更新评分
app.post('/api/ratings', async (req, res) => {
  try {
    const { filmId, userId, rating } = req.body
    if (!filmId || !userId || !rating) {
      return res.status(400).json({ success: false, error: '缺少必要参数' })
    }
    if (rating < 1 || rating > 5) {
      return res.status(400).json({ success: false, error: '评分必须在1-5之间' })
    }

    const connection = await pool.getConnection()
    try {
      // 检查是否已存在评分
      const [rows] = await connection.execute(
        'SELECT * FROM movie_ratings WHERE film_id = ? AND user_id = ?',
        [filmId, userId]
      )
      
      if (rows.length > 0) {
        // 更新现有评分
        await connection.execute(
          'UPDATE movie_ratings SET rating = ?, update_time = NOW() WHERE film_id = ? AND user_id = ?',
          [rating, filmId, userId]
        )
      } else {
        // 添加新评分
        await connection.execute(
          'INSERT INTO movie_ratings (film_id, user_id, rating, create_time, update_time) VALUES (?, ?, ?, NOW(), NOW())',
          [filmId, userId, rating]
        )
      }
      
      res.json({ success: true })
    } finally {
      connection.release()
    }
  } catch (error) {
    console.error('添加/更新评分失败:', error)
    res.status(500).json({ success: false, error: error.message })
  }
})

// 获取用户评分
app.get('/api/ratings/:filmId/:userId', async (req, res) => {
  try {
    const { filmId, userId } = req.params
    const connection = await pool.getConnection()
    
    try {
      const [rows] = await connection.execute(
        'SELECT rating FROM movie_ratings WHERE film_id = ? AND user_id = ?',
        [filmId, userId]
      )
      console.log('getUserRating - DB rows:', rows);
      res.json({ rating: rows.length > 0 ? rows[0].rating : 0 })
    } finally {
      connection.release()
    }
  } catch (error) {
    console.error('获取用户评分失败:', error)
    res.status(500).json({ error: error.message })
  }
})

// 获取平均评分
app.get('/api/ratings/:filmId/average', async (req, res) => {
  try {
    const { filmId } = req.params
    const connection = await pool.getConnection()
    
    try {
      const [rows] = await connection.execute(
        'SELECT AVG(rating) as averageRating FROM movie_ratings WHERE film_id = ?',
        [filmId]
      )
      console.log('getAverageRating - DB rows:', rows);
      res.json({ averageRating: rows[0].averageRating || 0 })
    } finally {
      connection.release()
    }
  } catch (error) {
    console.error('获取平均评分失败:', error)
    res.status(500).json({ error: error.message })
  }
})

// 启动服务器
async function startServer() {
  try {
    // 测试数据库连接
    await testDatabaseConnection()
    
    // 启动服务器
    app.listen(port, '0.0.0.0', () => {
      console.log(`服务器运行在 http://0.0.0.0:${port}`)
      console.log('数据库配置:', dbConfig)
    })
  } catch (error) {
    console.error('服务器启动失败:', error)
    process.exit(1)
  }
}

startServer() 